// pages/member/CommodityEditor/CommodityEditor.js
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    store_id: '',
    sectionOptions: [],
    uploadUrl: '',
    objectMultiArray: [],
    multiIndex: [0, 0, 0],
    regional: '请选择商品分类',
    cargon_data: {
      title: "",
      sku: "",
      thumb: "",
      price: "",
      market_price: "",
      cost_price: "",
      stock: "",
    },
    goods_id: '',
    imageUrl: "",
    fileList1: [],
    fileList2: [],
    upNumMax: 0,
    selectedOptions3: [],
    jumpState: true,
    imgPath: app.globalData.imgPath
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.store) {
      this.setData({
        store: options.store
      });
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id
      });
    }
    if (options.goods_id) {
      this.setData({
        goods_id: options.goods_id
      });
    }
    this._urlUp();
    this._getClassifyJson();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {

  },
  //选择分类对接数据
  _getClassifyJson() {
    let that = this;
    if (that.data.store == "store") {
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.goods-category.get-category-by-store-id");
      urlStr += '&store_id=' + that.data.store_id;
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let sectionOptionsData = [];
            for (let i = 0; i < res.data.list.length; i++) {
              sectionOptionsData.push({
                id: res.data.list[i].id,
                name: res.data.list[i].name,
                children: []
              });
              for (let k = 0; k < res.data.list[i].childrens.length; k++) {
                sectionOptionsData[i].children.push({
                  id: res.data.list[i].childrens[k].id,
                  name: res.data.list[i].childrens[k].name
                });
              }
            }
            that.setData({
              sectionOptions: sectionOptionsData
            });
            that.goodsHandlefunction();
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
          that.getGoodsJson();
        },
        fail: function(res) {
          console.log(res.msg);
        },
      });
    } else if (that.data.store == "supplier") {
      let urlStr = app.getNetAddresss("plugin.supplier.frontend.goods.get-category");
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {},
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let sectionOptionsData = [];
            for (var i = 0; i < res.data.length; i++) {
              sectionOptionsData.push({
                id: res.data[i].id,
                name: res.data[i].name,
                children: []
              });
              if (!res.data[i].childrens || res.data[i].childrens.length < 1) {
                // 判断是否有二级分类
              } else {
                // that.sectionOptions[i].children = [];
                for (let k = 0; k < res.data[i].childrens.length; k++) {
                  sectionOptionsData[i].children.push({
                    id: res.data[i].childrens[k].id,
                    name: res.data[i].childrens[k].name,
                    children: []
                  });
                  if (!res.data[i].childrens[k].childrens || res.data[i].childrens[k].childrens.length < 1) {
                    // 判断是否有三级分类
                  } else {
                    for (var j = 0; j < res.data[i].childrens[k].childrens.length; j++) {
                      sectionOptionsData[i].children[k].children.push({
                        id: res.data[i].childrens[k].childrens[j].id,
                        name: res.data[i].childrens[k].childrens[j].name
                      });
                    }
                  }
                }
              }
            }
            that.setData({
              sectionOptions: sectionOptionsData
            });
            that.goodsHandlefunction();
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
          that.getGoodsJson();
        },
        fail: function(res) {}
      });
    }
  },
  //商品图片上传
  _urlUp() {
    if (this.data.store == "store") {
      this.setData({
        uploadUrl: 'plugin.store-cashier.frontend.store.goods.upload'
      });
    } else if (this.data.store == "supplier") {
      this.setData({
        uploadUrl: 'plugin.supplier.frontend.goods.upload'
      });
    }
  },
  goodsHandlefunction() {
    let sectionOptions = this.data.sectionOptions;
    let arr_1 = [];
    let arr_2 = [];
    let arr_3 = [];
    for (let i = 0; i < sectionOptions.length; i++) {
      arr_1.push({

        id: sectionOptions[i].id,
        name: sectionOptions[i].name

      });
    }
    if (sectionOptions[0].children.length > 0) {
      for (let k = 0; k < sectionOptions[0].children.length; k++) {
        arr_2.push({
          id: sectionOptions[0].children[k].id,
          name: sectionOptions[0].children[k].name
        });
      }
    }
    if ((sectionOptions[0].children && sectionOptions[0].children.length > 0) && (sectionOptions[0].children[0].children &&
				sectionOptions[0].children[0].children.length > 0)) {
      for (let j = 0; j < sectionOptions[0].children[0].children.length; j++) {
        arr_3.push({
          id: sectionOptions[0].children[0].children[j].id,
          name: sectionOptions[0].children[0].children[j].name
        });
      }
    }
    this.setData({
      'objectMultiArray[0]': arr_1,
      'objectMultiArray[1]': arr_2,
      'objectMultiArray[2]': arr_3,
    });
  },
  //获取数据
  getGoodsJson() {
    let that = this;
    var urlStr = "";
    var json = {};
    if (that.data.store == "store") {
      urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.goods.get-goods-detail");
      json = {
        goods_id: that.data.goods_id
      };
    } else if (that.data.store == "supplier") {
      urlStr = app.getNetAddresss("plugin.supplier.frontend.goods.goods-detail");
      json = {
        goods_id: that.data.goods_id
      };
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let selectedOptions3 = that.data.selectedOptions3;
          if (res.data.category_ids.parentid) {
            selectedOptions3.push(Number(res.data.category_ids.parentid));
          }
          if (res.data.category_ids.childid) {
            selectedOptions3.push(Number(res.data.category_ids.childid));
          }
          if (res.data.category_ids.thirdid) {
            selectedOptions3.push(Number(res.data.category_ids.thirdid));
          }
          that.setData({
            selectedOptions3: selectedOptions3
          });
          if (
            res.data.thumb_url != null &&
						res.data.thumb_url != ""
          ) {
            let fileList1 = that.data.fileList1;
            let fileList2 = that.data.fileList2;
            for (var i = 0; i < res.data.thumb_url.length; i++) {
              fileList1.push({
                url: res.data.thumb_url[i]
              });
              fileList2.push({
                url: res.data.thumb_url[i]
              });
            }
            that.setData({
              fileList1: fileList1,
              fileList2: fileList2,
              upNumMax: res.data.thumb_url.length
            });
          }
          that.setData({
            'cargon_data.title': res.data.title,
            'cargon_data.sku': res.data.sku,
            'imageUrl': res.data.thumb,
            'cargon_data.thumb': res.data.thumb,
            'cargon_data.price': res.data.price,
            'cargon_data.market_price': res.data.market_price,
            'cargon_data.cost_price': res.data.cost_price,
            'cargon_data.stock': res.data.stock
          });
          //初始化分类选择
          that.commodityInit();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function(res) {}
    });
  },
  //商品名称值绑定
  titleinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.title': val
    });
  },
  //商品单位值绑定
  skuinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.sku': val
    });
  },
  //商品现价值绑定
  priceinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.price': val
    });
  },
  //商品原价值绑定
  marketpriceinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.market_price': val
    });
  },
  //商品成本值绑定
  costPriceinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.cost_price': val
    });
  },
  //商品库存值绑定
  stockinp(e) {
    let val = e.detail.value;
    this.setData({
      'cargon_data.stock': val
    });
  },
  //选择图片
  onRead_1() {
    if (this.data.upNumMax == 4 || this.data.upNumMax >= 4) {
      wx.showToast({
        icon: 'none',
        title: '图片数量已达到上限',
        duration: 1500
      });
      return false;
    }
    let that = this;
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    urlStr += '&3rd_session=' + session;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            let photourl = e.tempFilePath;
            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              formData: {
                attach: 'upload'
              },
              header:{
                "Content-Type": "multipart/form-data",
                Cookie: "PHPSESSID=" + wx_token,
              },
              success(resdata) {
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  let fileList1 = that.data.fileList1;
                  let fileList2 = that.data.fileList2;
                  fileList1.push({
                    url: res.data.img
                  });
                  fileList2.push({
                    url: photourl
                  });
                  that.setData({
                    upNumMax: that.data.upNumMax + 1,
                    fileList1: fileList1,
                    fileList2: fileList2
                  });
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {

          },
          complete(e) {

          }
        });
      }
    });
  },
  removeImg: function(e) {
    let index = e.currentTarget.dataset.index;
    let fileList1 = this.data.fileList1;
    let fileList2 = this.data.fileList2;
    fileList1.splice(index, 1);
    fileList2.splice(index, 1);
    this.setData({
      fileList1: fileList1,
      fileList2: fileList2
    });
    this.setData({
      upNumMax: this.data.fileList1.length
    });
  },
  commodityInit() {
    let selectedOptions3 = this.data.selectedOptions3;
    let sectionOptions = this.data.sectionOptions;
    let arr_2 = [];
    let arr_3 = [];
    let str = '';
    for (let i = 0; i < sectionOptions.length; i++) {
      if (sectionOptions[i].id == selectedOptions3[0]) {
        this.setData({
          'multiIndex[0]': i
        });
        str += sectionOptions[i].name;
        break;
      }
    }
    if (sectionOptions[this.data.multiIndex[0]].children.length > 0) {
      for (let k = 0; k < sectionOptions[this.data.multiIndex[0]].children.length; k++) {
        arr_2.push({
          id: sectionOptions[this.data.multiIndex[0]].children[k].id,
          name: sectionOptions[this.data.multiIndex[0]].children[k].name
        });
      }
    }
    this.setData({
      'objectMultiArray[1]': arr_2
    });
    if (sectionOptions[this.data.multiIndex[0]].children.length > 0) {
      for (let k = 0; k < sectionOptions[this.data.multiIndex[0]].children.length; k++) {
        if (sectionOptions[this.data.multiIndex[0]].children[k].id == selectedOptions3[1]) {
          this.setData({
            'multiIndex[1]': k
          });
          str += '/' + sectionOptions[this.data.multiIndex[0]].children[k].name;
          break;
        }
      }
    }
    if ((sectionOptions[this.data.multiIndex[0]].children && sectionOptions[this.data.multiIndex[0]].children.length >
				0) && (sectionOptions[this.data.multiIndex[0]].children[
      this.data.multiIndex[1]].children && sectionOptions[this.data.multiIndex[0]].children[
      this.data.multiIndex[1]].children.length > 0)) {
      for (let j = 0; j < sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children.length; j++) {
        arr_3.push({
          id: sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children[j].id,
          name: sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children[j].name
        });
      }
    }
    this.setData({
      'objectMultiArray[2]': arr_3
    });
    if ((sectionOptions[this.data.multiIndex[0]].children && sectionOptions[this.data.multiIndex[0]].children.length >
				0) && (sectionOptions[this.data.multiIndex[0]].children[
      this.data.multiIndex[1]].children && sectionOptions[this.data.multiIndex[0]].children[
      this.data.multiIndex[1]].children.length > 0)) {
      for (let j = 0; j < sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children.length; j++) {
        if (sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children[j].id == selectedOptions3[
          2]) {
          this.setData({
            'multiIndex[1]': j
          });
          str += '/' + sectionOptions[this.data.multiIndex[0]].children[this.data.multiIndex[1]].children[j].name;
          break;
        }
      }
    }
    this.setData({
      regional: str
    });
  },
  commodityBtn(e) {
    let column = e.detail.column;
    let val = e.detail.value;
    const data = {
      multiArray: this.data.objectMultiArray,
    };
    this.setData({
      ['multiIndex[' + column + ']']: val
    });
    switch (column) {
    case 0:
      this.selecommodity_0(val);
      break;
    case 1:
      this.selecommodity_1(this.data.multiIndex[0], val);
      break;
    case 2:
      break;
    }
    this.setData(data);
  },
  commodityconfirm(e) {
    let sectionOptions = this.data.sectionOptions;
    let indexArray = e.detail.value;
    let index_0 = indexArray[0];
    let index_1 = indexArray[1];
    let index_2 = indexArray[2];
    let idArray = [];
    let strArray = [];
    if (sectionOptions.length > 0) {
      idArray.push(sectionOptions[index_0].id);
      strArray.push(sectionOptions[index_0].name);
      if (sectionOptions[index_0].children.length > 0) {
        idArray.push(sectionOptions[index_0].children[index_1].id);
        strArray.push(sectionOptions[index_0].children[index_1].name);
        if (sectionOptions[index_0].children[index_1].children && sectionOptions[index_0].children[index_1].children.length >
					0) {
          idArray.push(sectionOptions[index_0].children[index_1].children[index_2].id);
          strArray.push(sectionOptions[index_0].children[index_1].children[index_2].name);
        }
      }
    }
    this.setData({
      'regional': strArray.join('/'),
      selectedOptions3: idArray
    });
  },
  selecommodity_0(index) {
    let sectionOptions = this.data.sectionOptions;
    let arr_2 = [];
    let arr_3 = [];
    if (sectionOptions[index].children.length > 0) {
      for (let k = 0; k < sectionOptions[index].children.length; k++) {
        arr_2.push({
          id: sectionOptions[index].children[k].id,
          name: sectionOptions[index].children[k].name
        });
      }
    }
    if ((sectionOptions[index].children && sectionOptions[index].children.length > 0) && (sectionOptions[index].children[
      0].children && sectionOptions[index].children[0].children.length > 0)) {
      for (let j = 0; j < sectionOptions[index].children[0].children.length; j++) {
        arr_3.push({
          id: sectionOptions[index].children[0].children[j].id,
          name: sectionOptions[index].children[0].children[j].name
        });
      }
    }
    this.setData({
      'objectMultiArray[1]': arr_2,
      'objectMultiArray[2]': arr_3,
      'multiIndex[1]': 0,
      'multiIndex[2]': 0
    });
  },
  selecommodity_1(index_0, index_1) {
    let sectionOptions = this.data.sectionOptions;
    let arr_3 = [];
    if ((sectionOptions[index_0].children && sectionOptions[index_0].children.length > 0) && (sectionOptions[index_0].children[
      index_1].children && sectionOptions[index_0].children[index_1].children.length > 0)) {
      for (let j = 0; j < sectionOptions[index_0].children[index_1].children.length; j++) {
        arr_3.push({
          id: sectionOptions[index_0].children[index_1].children[j].id,
          name: sectionOptions[index_0].children[index_1].children[j].name
        });
      }
    }
    this.setData({
      'objectMultiArray[2]': arr_3,
      'multiIndex[2]': 0
    });
  },
  //确认发布
  confirmationEditor() {
    var that = this;
    that.jumpEvent();
    if (that.data.jumpState == true) {
      var newArr = [];
      if (that.data.fileList1.length != 0) {
        for (let i = 0; i < that.data.fileList1.length; i++) {
          newArr.push(that.data.fileList1[i].url);
        }
      } else {
        newArr = [];
      }
      let urlStr = "";
      let json = {};
      if (that.data.store == "store") {
        urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.goods.edit-goods");
        json = {
          store_id: that.data.store_id,
          goods_id: that.data.goods_id,
          category_pid: that.data.selectedOptions3[0],
          category_cid: that.data.selectedOptions3[1],
          title: that.data.cargon_data.title,
          thumb: that.data.cargon_data.thumb,
          thumb_url: newArr,
          cost_price: that.data.cargon_data.cost_price,
          market_price: that.data.cargon_data.market_price,
          price: that.data.cargon_data.price,
          sku: that.data.cargon_data.sku,
          stock: that.data.cargon_data.stock
        };
      } else if (that.data.store == "supplier") {
        urlStr = app.getNetAddresss("plugin.supplier.frontend.goods.edit-goods");
        json = {
          title: that.data.cargon_data.title,
          goods_id: that.data.goods_id,
          thumb: that.data.cargon_data.thumb,
          thumb_url: newArr,
          cost_price: that.data.cargon_data.cost_price,
          market_price: that.data.cargon_data.market_price,
          price: that.data.cargon_data.price,
          sku: that.data.cargon_data.sku,
          stock: that.data.cargon_data.stock
        };
        if (that.data.selectedOptions3.length < 2) {
          wx.showToast({
            icon: 'none',
            title: '必须选择二级分类',
            duration: 1500
          });
          return;
        } else if (that.data.selectedOptions3.length < 3) {
          json.category_pid = that.data.selectedOptions3[0];
          json.category_cid = that.data.selectedOptions3[1];
        } else {
          json.category_pid = that.data.selectedOptions3[0];
          json.category_cid = that.data.selectedOptions3[1];
          json.category_tid = that.data.selectedOptions3[2];
        }
      }
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              title: '上传商品成功',
              icon: 'none',
              duration: 1500,
              success: function() {
                setTimeout(function() {
                  //要延时执行的代码
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1500); //延迟时间
              },
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }

        },
        fail: function(res) {}
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '商品信息不完整',
        duration: 1500
      });
    }
  },
  //跳转测试
  jumpEvent() {
    this.setData({
      jumpState: true
    });
    for (let item in this.data.cargon_data) {
      if (this.data.cargon_data[item] == "") {
        this.setData({
          jumpState: false
        });
      }
    }
    if (this.data.selectedOptions3.length == 0) {
      this.setData({
        jumpState: false
      });
    }
    if (this.data.imageUrl == "") {
      this.setData({
        jumpState: false
      });
    }
  },
  //选择图片
  onRead() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            let photourl = e.tempFilePath;
            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              success(resdata) {
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  that.setData({
                    imageUrl: photourl,
                    'cargon_data.thumb': res.data.img
                  });
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {

          },
          complete(e) {

          }
        });
      }
    });
  },
});
